package com.yxj.dries.lib.network;

import com.yxj.dries.lib.network.https.HttpsUtils;
import com.yxj.dries.lib.network.listener.DisposeDataHandle;
import com.yxj.dries.lib.network.response.CommonFileCallback;
import com.yxj.dries.lib.network.response.CommonJsonCallback;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author ZSY
 */
public class CommonOkHttpClient {

    private static final OkHttpClient okHttpClient;
    private static String sBaseUrl;
    private static final int TIME_OUT = 30;

    // 初始化OkHttpClient
    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        /**
         * 添加公共请求头
         */
        builder.addInterceptor(new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                Request request = chain.request();
                request.newBuilder().addHeader("User-Agent", "TEST").build();
                return chain.proceed(request);
            }
        });

        builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
        // 允许重定向
        builder.followRedirects(true);


        // trust all the https point
        builder.sslSocketFactory(
                HttpsUtils.initSSLSocketFactory(),
                HttpsUtils.initTrustManager()
        );

        okHttpClient = builder.build();

    }

    public static Call get(DisposeDataHandle handle, Request request) {
        Call call = okHttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handle));
        return call;
    }

    public static Call post(DisposeDataHandle handle, Request request) {
        Call call = okHttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handle));
        return call;
    }

    public static Call downloadFile(DisposeDataHandle handle, Request request) {
        Call call = okHttpClient.newCall(request);
        call.enqueue(new CommonFileCallback(handle));
        return call;
    }

}
